<template>
  <view>
    <el-select
      v-if="
        util_GetRowAttrVal(rowData, rowIdx, metaItem, ['componentAttr', 'customizeOptionStyle'], '') !==
        'BuildInTreeSelect'
      "
      v-model="curBindVal"
      v-bind="allCompAttrs"
      v-on="allBindEvents"
    >
      <template
        v-if="
          util_GetRowAttrVal(rowData, rowIdx, metaItem, ['componentAttr', 'customizeOptionStyle'], '') === 'TreeSelect'
        "
      >
        <TreeOption
          :options="util_GetRowAttrVal(rowData, rowIdx, metaItem, ['options'], [])"
          :tree-option-config="util_GetRowAttrVal(rowData, rowIdx, metaItem, ['componentAttr', 'treeOptionConfig'], {})"
          :size="computedSizeComponentAttr"
        ></TreeOption>
      </template>
      <template v-else>
        <el-option
          v-if="
            util_GetRowAttrVal(rowData, rowIdx, metaItem, ['componentAttr', 'customizeOptionStyle'], '') ===
            'WithAddBtn'
          "
          :label="''"
          :value="''"
        >
          <view @click="isShowContainer = true">
            <GdIcon icon-name="plus"></GdIcon>
            {{ addBtnText }}
          </view>
        </el-option>
        <el-option
          v-for="option in util_GetRowAttrVal(rowData, rowIdx, metaItem, ['options'], [])"
          :key="option.value + rowIdx"
          :label="option.label"
          :value="option.value"
        />
      </template>
    </el-select>
    <el-tree-select
      v-else
      v-model="curBindVal"
      :data="util_GetRowAttrVal(rowData, rowIdx, metaItem, ['options'], [])"
      v-bind="allCompAttrs"
      v-on="allBindEvents"
    >
      <template
        #default="slotProps"
        v-if="
          allCompAttrs['default-slot-config'] &&
          allCompAttrs['default-slot-config'].hasOwnProperty('contentType') &&
          allCompAttrs['default-slot-config'].hasOwnProperty('value')
        "
      >
        <template v-if="allCompAttrs['default-slot-config'].contentType === 'Text'">
          <view
            v-on="getBindSlotEvents('default-slot-config')"
            :style="allCompAttrs['default-slot-config']?.style ?? {}"
          >
            {{ allCompAttrs["default-slot-config"].value }}
          </view>
        </template>
        <template v-else-if="allCompAttrs['default-slot-config'].contentType === 'CustomizeComp'">
          <gd-enhance-hack-dynmic-comp
            :component-file-path="allCompAttrs['default-slot-config'].value.componentFilePath"
            :root-path-type="'customize'"
            :component-props="{ ...props, curBindVal, slotProps }"
            v-bind="$attrs"
            v-on="getBindSlotEvents('default-slot-config')"
          ></gd-enhance-hack-dynmic-comp>
        </template>
        <template v-else-if="allCompAttrs['default-slot-config'].contentType === 'Icon'">
          <gd-icon
            :icon-name="allCompAttrs['default-slot-config'].value"
            v-bind="{ ...$attrs, ...(allCompAttrs['default-slot-config']?.componentAttr ?? {}) }"
          ></gd-icon>
        </template>
      </template>
    </el-tree-select>
    <teleport to="body">
      <GdContainerWithBtns
        v-model:isShowContainer="isShowContainer"
        :container-attr="containerAttr"
        @do-operation="doOperationContainer"
      >
        <SceneContainerForm
          :meta-item-list="containerFormItemMetaList"
          :meta-dynmic-config-list="containerMetaDynmicConfigList"
          :form-data="containerFormData"
        ></SceneContainerForm>
      </GdContainerWithBtns>
    </teleport>
  </view>
</template>
<script>
  export default {
    inheritAttrs: false,
    name: "DismensionGdSelect",
  };
</script>
<script setup>
  // #ifdef H5
  //import { ElTreeSelect } from 'element-plus'
  //import 'element-plus/theme-chalk/el-tree-select.css'
  // #endif
  import { computed, watch, ref, reactive, inject } from "vue";
  import useComponentAttrs, { embeddedAtomicCompProps } from "../../useComponentAttrs";
  import useComponentEvents from "../../useComponentEvents";
  import {
    util_GetRowAttrVal,
    util_OptionChainHack,
    util_GetCurComponentAttrWithInheritedAttr,
  } from "@gd-accbuild-ui/gd-ui/utils/index";

  import TreeOption from "./components/tree-option/index.vue";

  import GdIcon from "@gd-accbuild-ui/gd-ui/gd-icon/gd-icon.vue";
  import SceneContainerForm from "@gd-accbuild-ui/scene-container/scene-container-form/scene-container-form.vue";
  import GdContainerWithBtns from "@gd-accbuild-ui/gd-ui/gd-container-with-btns/gd-container-with-btns.vue";

  import useSetDynmicSelectOptions from "../../useFromDynmicConfig/useFromOptionsConfig";

  import { globalConfig } from "@gd-accbuild-core/config";
  import { isSuccessReqBackend } from "@gd-accbuild-core/config/utils";

  const props = defineProps({
    ...embeddedAtomicCompProps,
  });

  useSetDynmicSelectOptions(props);

  //组件所有属性的默认值映射
  const compAttrsKeyDefaultValueMapping = {
    style: {},
    placeholder: "",
    multiple: false,
    collapseTags: false,
    teleported: false,
    popperAppendToBody: true,
    customizeOptionStyle: undefined, //"BuildInTreeSelect" | "TreeSelect"
    ////
    checkStrictly: false,
    renderAfterExpand: false,
    showCheckbox: false,
    props: {
      label: "label",
      value: "value",
      children: "children",
      isLeaf: "isLeaf",
    },
    ////
    defaultSlotConfig: {},
    //继承属性
    size: "default",
    disabled: false,
  };

  const { curBindVal, containerType, allCompAttrs } = useComponentAttrs({
    props,
    compAttrsKeyDefaultValueMapping,
  });
  const { allBindEvents, getBindSlotEvents } = useComponentEvents(props, curBindVal);

  const allSlotUiConfigInPanel = [{ key: "defaultSlotConfig", slotConfig: { slotName: "default" } }];
  const getSlotMetaKeyBySlotName = (slotName) => {
    const matchedUiConfig = allSlotUiConfigInPanel.find((el) => el.slotConfig.slotName === slotName);
    if (matchedUiConfig) {
      return matchedUiConfig.key;
    } else {
      return "";
    }
  };

  const computedSizeComponentAttr = computed(() => {
    return util_GetCurComponentAttrWithInheritedAttr(
      props.rowData,
      props.rowIdx,
      props.metaItem,
      ["componentAttr", "size"],
      "default",
      props.commonAttr
    );
  });

  /**
   * select带新增按钮的逻辑
   */
  const isShowContainer = ref(false);
  const containerFormItemMetaList = computed(() => {
    return util_GetRowAttrVal(
      props.rowData,
      props.rowIdx,
      props.metaItem,
      ["componentAttr", "WithAddBtnConfig", "metaItemList"],
      []
    );
  });
  const containerMetaDynmicConfigList = computed(() => {
    return util_GetRowAttrVal(
      props.rowData,
      props.rowIdx,
      props.metaItem,
      ["componentAttr", "WithAddBtnConfig", "metaDynmicConfigList"],
      []
    );
  });
  const addBtnText = computed(() => {
    return util_GetRowAttrVal(
      props.rowData,
      props.rowIdx,
      props.metaItem,
      ["componentAttr", "WithAddBtnConfig", "text"],
      "添加"
    );
  });
  const containerAttr = computed(() => {
    return {
      containerStyle: "Dialog",
      title: addBtnText.value,
      appendToBody: util_GetRowAttrVal(
        props.rowData,
        props.rowIdx,
        props.metaItem,
        ["componentAttr", "WithAddBtnConfig", "appendToBody"],
        false
      ),
    };
  });

  const containerFormData = ref({});

  //TODO:FIXME: 暂时 Select里的 新增按钮提交的数据 仅支持VmCode
  const containerSubmitVmCode = computed(() => {
    return util_GetRowAttrVal(
      props.rowData,
      props.rowIdx,
      props.metaItem,
      ["componentAttr", "WithAddBtnConfig", "dataFromType"],
      null
    ) === "VmCode"
      ? util_GetRowAttrVal(
          props.rowData,
          props.rowIdx,
          props.metaItem,
          ["componentAttr", "WithAddBtnConfig", "vmCode"],
          null
        )
      : null;
  });
  const doOperationContainer = async (params) => {
    if (params.metaKey === "buildInContainerSubmitBtn") {
      const res = await globalConfig.save({
        moduleCode: props.vmTemplateConfig.moduleCode,
        vmCode: containerSubmitVmCode.value,
        data: containerFormData.value,
        vmTemplateConfig: props.vmTemplateConfig,
      });
      if (isSuccessReqBackend(res)) {
        isShowContainer.value = false;
        /* labelKeyAlias: "projectName",
      valueKeyAlias: "projectCode", */
        props.metaItem.options.push({
          label: containerFormData.value[props.metaDynmicConfig.optionsConfig.labelKeyAlias],
          value: containerFormData.value[props.metaDynmicConfig.optionsConfig.valueKeyAlias],
        });
        curBindVal.value = containerFormData.value[props.metaDynmicConfig.optionsConfig.valueKeyAlias];
      }
    }
  };
</script>
